package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/orm"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type CourseController struct {
	BaseController
}

func (u *CourseController) Prepare() {
	u.BaseController.Prepare()
	u.checkAuthor("DataGrid", "GetAddress")
}

func (u *CourseController) Index() {
	u.checkLogin()
	u.Data["pageTitle"] = "课程列表"
	u.ActiveSidebarUrl()
	u.Data["canEdit"] = u.checkActionAuthor(u.controllerName, "Edit")
	u.Data["canDelete"] = u.checkActionAuthor(u.controllerName, "Delete")
	u.Data["canCreateTab"] = u.checkActionAuthor(u.controllerName, "SettingTab")
	u.Data["canMatch"] = u.checkActionAuthor("CourseContentController", "Match")
	u.setTpl()
}

func (u *CourseController) DataGrid() {
	var params models.CourseQueryParam
	json.Unmarshal(u.Ctx.Input.RequestBody, &params)

	data, total := models.CoursePageList(&params)

	u.BootstrapJson(total, data)
}

func (u *CourseController) Edit() {
	if u.Ctx.Request.Method == "POST" {
		u.Save()
	}
	Id, _ := u.GetInt(":id", 0)
	m := &models.Course{}
	var err error
	if Id > 0 {
		m, err = models.CourseOne(Id)
		if err != nil {
			u.pageError("数据无效，请刷新后重试")
		}
	} else {
		m.Status = enums.Enabled
	}
	u.Data["m"] = m

	u.setTpl("course/edit", "shared/layout_pullbox")
}

func (u *CourseController) GetCityData() {
	data := models.GetCityDataList()
	u.jsonResult(enums.JRCodeSuccess, "", data)
}

func (u *CourseController) Save() {
	m := models.Course{}
	o := orm.NewOrm()
	var err error

	if err = u.ParseForm(&m); err != nil {
		u.jsonResult(enums.JRCodeFailed, "获取数据失败"+err.Error(), m.Id)
	}
	m.UpdateAt = time.Now().Unix()

	if m.Id == 0 {
		m.CreateAt = time.Now().Unix()
		if _, err := o.Insert(&m); err != nil {
			u.jsonResult(enums.JRCodeFailed, "添加失败"+err.Error(), m.Id)
		}
	} else {
		oM, err := models.CourseOne(m.Id)
		if err != nil {
			u.jsonResult(enums.JRCodeFailed, "数据无效，请刷新后重试", m.Id)
		} else {
			m.CreateAt = oM.CreateAt
			if _, err := o.Update(&m); err != nil {
				u.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
			}
		}
	}
	u.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
}

func (u *CourseController) GetAddress() {
	var params models.AddressParam
	params.Address = strings.TrimSpace(u.GetString("address"))
	params.Region = strings.TrimSpace(u.GetString("region"))

	urlPath, err := models.GetGeocoderAddress(&params)
	response, err := http.Get(urlPath)
	fmt.Println("你输入的是：", urlPath)
	if err != nil {
		u.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	myMap := make(map[string]string)
	json.Unmarshal(body, &myMap)
	u.jsonResult(enums.JRCodeSuccess, "", myMap)
}

func (u *CourseController) GetSuggestionAddress() {
	var params models.SuggestionParam
	params.Keyword = strings.TrimSpace(u.GetString("keyword"))
	params.Region = strings.TrimSpace(u.GetString("region"))

	urlPath, err := models.GetSuggestionAddress(&params)
	response, err := http.Get(urlPath)
	fmt.Println("你输入的是：", urlPath)
	if err != nil {
		u.jsonResult(enums.JRCodeFailed, err.Error(), "")
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	myMap := make(map[string]string)
	json.Unmarshal(body, &myMap)
	u.jsonResult(enums.JRCodeSuccess, "", myMap)
}

func (u *CourseController) Delete() {
	str := u.GetString("ids")
	ids := make([]int, 0, len(str))

	for _, item := range strings.Split(str, ",") {
		if id, err := strconv.Atoi(item); err == nil {
			ids = append(ids, id)
		}
	}

	query := orm.NewOrm().QueryTable(models.CourseTBName())
	if _, err := query.Filter("id__in", ids).Delete(); err == nil {
		u.jsonResult(enums.JRCodeSuccess, fmt.Sprintf("删除成功"), 0)
	} else {
		u.jsonResult(enums.JRCodeFailed, "删除失败", 0)
	}
}

func (u *CourseController) SettingTab() {
	if u.Ctx.Request.Method == "POST" {
		u.SaveSetting()
	}
	Id, _ := u.GetInt(":id", 0)
	if Id == 0 {
		u.pageError("不存在的信息")
	} else {

	}
	u.setTpl("course/setting_tab", "shared/layout_pullbox", "footer")
}

func (u *CourseController) SaveSetting() {
	var params []models.CourseItem
	json.Unmarshal(u.Ctx.Input.RequestBody, &params)

	fmt.Println(&params)
	m := make([]*models.CourseItem, 0)
	o := orm.NewOrm()
	successNums, err := o.InsertMulti(1, &params)
	fmt.Println(successNums)

	fmt.Println(u.Input())
	if err = u.ParseForm(&m); err != nil {
		u.jsonResult(enums.JRCodeFailed, "数据获取失败"+err.Error(), m)
	}
	fmt.Println(m)
}
